package lesson6.example1;

import java.lang.management.ClassLoadingMXBean;
import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryUsage;
import java.util.Arrays;
import java.util.List;

class JMXUtil {

    private static final long MB = 1048576L;

    static void printMemoryInfo() {
    	// 提供了整个虚拟机中内存的使用情况，包括 Java 堆(heap)和非 Java 
    	// 堆所占用的内存，提供当前等待 finalize 的对象数量，它甚至可以做 gc(实际上是调用 System.gc)
        MemoryMXBean memory = ManagementFactory.getMemoryMXBean();
        MemoryUsage headMemory = memory.getHeapMemoryUsage();
        String info = String.format("\ninit: %s\t max: %s\t used: %s\t committed: %s\t use rate: %s\n",
                headMemory.getInit() / MB + "MB",
                headMemory.getMax() / MB + "MB", headMemory.getUsed() / MB + "MB",
                headMemory.getCommitted() / MB + "MB",
                headMemory.getUsed() * 100 / headMemory.getCommitted() + "%"
        );

        System.out.print(info);

        MemoryUsage nonheadMemory = memory.getNonHeapMemoryUsage();
        info = String.format("init: %s\t max: %s\t used: %s\t committed: %s\t use rate: %s\n",
                nonheadMemory.getInit() / MB + "MB",
                nonheadMemory.getMax() / MB + "MB", nonheadMemory.getUsed() / MB + "MB",
                nonheadMemory.getCommitted() / MB + "MB",
                nonheadMemory.getUsed() * 100 / nonheadMemory.getCommitted() + "%"

        );
        System.out.println(info);
    }

    static void printGCInfo() {
    	// 仅仅提供了 GC 的次数和 GC 花费总时间的近似值
        List<GarbageCollectorMXBean> garbages = ManagementFactory.getGarbageCollectorMXBeans();
        for (GarbageCollectorMXBean garbage : garbages) {
            String info = String.format("name: %s\t count:%s\t took:%s\t pool name:%s",
                    garbage.getName(),
                    garbage.getCollectionCount(),
                    garbage.getCollectionTime(),
                    Arrays.deepToString(garbage.getMemoryPoolNames()));
            System.out.println(info);
        }
    }
    
    static void printClassLoadingMXBean(){
    	// 包括一些类的装载信息，比如有多少类已经装载/卸载(unloaded)，虚拟机类装载的 
    	// verbose 选项(即命令行中的 Java –verbose:class 选项)是否打开，还可以帮助用户打开/关闭该选项。
    	ClassLoadingMXBean clm = ManagementFactory.getClassLoadingMXBean();
    	System.out.println("total count："+clm.getTotalLoadedClassCount());
    	System.out.println("loaded count："+clm.getLoadedClassCount());
    	System.out.println("unloaded count："+clm.getUnloadedClassCount());
    }
    

}
